import { getSingleStore } from '../single-store';
import { ReuseComponentHandle, ReuseComponentRef, ReuseHookTypes } from './reuse-tab.interfaces';
import { globalStore } from '@ds/ds-micro/dist';
/* 以下在执行代码里面加上延时器，500秒，主要是当前页，离开，
未存储进入handles中,导致销毁不了当前页，让其先存储进入后在执行销毁或者全部清除动作*/
export class AppReuseStrategy {
  public static lastUrl = ''; // 保存上一个路由
  public static currentUrl = ''; // 当前路由
  public static isReload = false; // 是否reload路由

  constructor() {}

  // public deleteRouteSnapshot(url: string): void {
  //   setTimeout(() => {
  //     const name = this.getReplaceUrl(url);
  //     if (this.handlers[name]) {
  //       // @ts-ignore
  //      globalStore('cacheRouter')[name].componentRef.destroy();
  //       deleteglobalStore('cacheRouter')[name];
  //     }
  //   }, 500);
  // }

  // public deleteRouteSnapshotSync(url: string): void {
  //   const name = url.replace(/\//g, '_');
  //   if (this.handlers[name]) {
  //     // @ts-ignore
  //    globalStore('cacheRouter')[name].componentRef.destroy();
  //     deleteglobalStore('cacheRouter')[name];
  //   }
  //   console.info('删除路由快照:', name);
  // }

  // // 清除全部路由缓存
  // public clear(): void {
  //   setTimeout(() => {
  //     // tslint:disable-next-line: forin
  //     for (const key inglobalStore('cacheRouter')) {
  //       // @ts-ignore
  //       if (this.handlers[key]) {
  //        globalStore('cacheRouter')[key]['componentRef'].destroy();
  //       }
  //       deleteglobalStore('cacheRouter')[key];
  //     }
  //     console.info('删除全部快照',globalStore('cacheRouter'));
  //   }, 500);
  // }

  /** 表示对所有路由允许复用 如果你有路由不想利用可以在这加一些业务逻辑判断 */
  public shouldDetach(route: any): boolean {
    // tslint:disable-next-line: curly
    if (this.hasInValidRoute(route)) return false;
    if (route['_routerState'].url === '/') {
      // 根路由不复用
      return false;
    }
    // return false;
    return true;
  }
  /** 当路由离开时会触发。按path作为key存储路由快照&组件当前实例对象 */
  public store(_route: any, handle: ReuseComponentHandle): void {
    if (handle && handle.componentRef) {
      this.runHook('_onReuseDestroy', handle.componentRef);
    }
    if (handle) {
      console.log('----------------------储存路由:', globalStore('cacheRouter'), getSingleStore('systemData').value.id, handle);
      // globalStore('cacheRouter')[this.getRouteUrl(route)] = handle;
      globalStore('cacheRouter')[this.getAppUrl()] = handle;
    }
  }

  /** 若 path 在缓存中有的都认为允许还原路由 */
  public shouldAttach(route: any): boolean {
    // tslint:disable-next-line: curly
    if (this.hasInValidRoute(route)) return false;
    const localCompRef: any = globalStore('cacheRouter')[this.getRouteUrl(route)];
    if (localCompRef) {
      this.runHook('_onReuseInit', localCompRef.componentRef);
    }
    AppReuseStrategy.isReload = !!globalStore('cacheRouter')[this.getRouteUrl(route)];
    return AppReuseStrategy.isReload;
  }

  /** 从缓存中获取快照，若无则返回null */
  public retrieve(route: any): any {
    if (this.hasInValidRoute(route)) {
      return null;
    }
    // console.log(getSingleStore('systemData').value.host, globalStore('cacheRouter'), this.getRouteUrl(route), '===================');
    // return globalStore('cacheRouter')[this.getRouteUrl(route)];
    return null;
  }

  /** 进入路由触发，判断是否同一路由 */
  public shouldReuseRoute(future: any, curr: any): boolean {
    // todo 通知全局路由离开了
    AppReuseStrategy.lastUrl = future.routeConfig?.path ?? '';
    AppReuseStrategy.currentUrl = curr.routeConfig?.path ?? '';
    return future.routeConfig === curr.routeConfig && JSON.stringify(future.params) == JSON.stringify(curr.params);
  }

  public getReplaceUrl(url: string) {
    return url ? url.replace(/https:\/\/|http:\/\//, '').replace(/\/|\-|\:|\./g, '_') : '';
  }

  private getRouteUrl(route: string) {
    return (
      this.getReplaceUrl(getSingleStore('systemData').value.id) + '_' + this.getReplaceUrl(getSingleStore('systemData').value.host) + '_' + this.getReplaceUrl(this.getUrl(route))
    );
  }

  private getAppUrl() {
    return this.getReplaceUrl(getSingleStore('systemData').value.id) + '_' + this.getReplaceUrl(getSingleStore('systemData').value.host);
  }

  hasInValidRoute(route) {
    return !route.routeConfig || !!route.routeConfig.loadChildren || !!route.routeConfig.children;
  }

  /**
   * 根据快照获取URL地址
   */
  getUrl(route) {
    let next = this.getTruthRoute(route);
    const segments = [];
    while (next) {
      segments.push(next.url.join('/'));
      next = next.parent;
    }
    const url =
      '/' +
      segments
        .filter(i => i)
        .reverse()
        .join('/');
    return url;
  }

  getTruthRoute(route) {
    let next = route;
    // tslint:disable-next-line:curly
    while (next.firstChild) next = next.firstChild;
    return next;
  }

  runHook(method: ReuseHookTypes, comp: ReuseComponentRef): void {
    const compThis = comp?.instance;
    if (comp == null || !compThis) {
      return;
    }
    const fn = compThis[method];
    if (typeof fn !== 'function') {
      return;
    }

    (fn as () => void).call(compThis);
  }
}
